<template>
  <Tabs v-model:activeKey="activeKey" @change="handleTabChange">
    <TabPane key="basic" :tab="t('routes.demo.partManagerSettings.Property')">
      <div class="form-container">
        <div v-for="(part, index) in partData" :key="index" class="part-section">
          <Divider orientation="left">
            <Tag color="processing">{{ part.groupName }}</Tag>
          </Divider>
          <BasicForm
            :labelCol="{ span: 8 }"
            :wrapperCol="{ span: 16 }"
            :schemas="getSchemas(part.groupName, part.propList)"
            :showActionButtonGroup="false"
            @register="(form) => registerForm(form, index)"
          />
        </div>
      </div>
    </TabPane>
    <TabPane key="attachment" :tab="t('routes.demo.partManagerSettings.Attachment')">
      <BasicTable @register="registerAttachmentTable">
        <template #toolbar>
          <a-button type="primary" @click="CreatePartDetailAttachment" :disabled="isDisabled">
            {{ t('routes.demo.partManager.partDetailModal.addAttachment') }}
          </a-button>
        </template>
        <!-- 操作 -->
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:delete-outlined',
                tooltip: t('common.delete'),
                color: 'error',
                disabled: isDisabled,
                popConfirm: {
                  title: t('common.confirmDelete'),
                  confirm: DeletePartDetailAttachment.bind(null, record),
                },
              },
              // 修改
              {
                icon: 'ant-design:edit-outlined',
                tooltip: t('common.edit'),
                color: 'default',
                disabled: isDisabled,
                onClick: EditAssociated.bind(null, record),
                ifShow: props.isUpdate,
              },
              // 浏览
              {
                icon: 'ant-design:eye-outlined',
                tooltip: t('common.preview'),
                color: 'default',
                disabled: isDisabled,
                onClick: ViewAssociated.bind(null, record, '附件'),
                ifShow: props.isUpdate,
              },
              // 下载
              {
                icon: 'ant-design:download-outlined',
                tooltip: t('common.download'),
                color: 'default',
                disabled: isDisabled,
                onClick: DownloadAssociated.bind(null, record),
                ifShow: props.isUpdate,
              },
              // 版本展示
              {
                icon: 'ant-design:profile-outlined',
                tooltip: t('common.view'),
                color: 'default',
                disabled: isDisabled,
                onClick: VersionAssociated.bind(null, record),
                ifShow: props.isUpdate,
              },
            ]"
          />
        </template>
      </BasicTable>
    </TabPane>
    <TabPane key="related" :tab="t('routes.demo.partManagerSettings.Associated')">
      <BasicTable @register="registerAssociatedTable">
        <template #toolbar>
          <a-button type="primary" @click="CreateAssociated" :disabled="isDisabled">
            {{ t('common.create') }}
          </a-button>
          <a-button type="primary" @click="CreateCommonMap" :disabled="isDisabled">
            {{ t('routes.demo.partManager.partDetailModal.createSharedFigureDoc') }}
          </a-button>
        </template>
        <!-- 操作 -->
        <template #action="{ record }">
          <TableAction
            :actions="[
              // 删除
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                disabled: isDisabled,
                popConfirm: {
                  title: t('common.confirmDelete'),
                  confirm: DeleteAssociated.bind(null, record),
                },
              },
              // 浏览
              {
                icon: 'ant-design:eye-outlined',
                tooltip: t('common.preview'),
                color: 'default',
                disabled: isDisabled,
                onClick: ViewAssociated.bind(null, record, '关联'),
                ifShow: props.isUpdate,
              },
            ]"
          />
        </template>
      </BasicTable>
    </TabPane>
    <TabPane key="processFile" :tab="t('routes.demo.partManagerSettings.craftFile')">
      <BasicTable @register="craftFileTable">
        <!-- 操作 -->
        <template #action="{ record }">
          <TableAction
            :actions="[
              // 浏览
              {
                icon: 'ant-design:eye-outlined',
                tooltip: t('common.preview'),
                color: 'default',
                disabled: isDisabled,
                onClick: ViewAssociated.bind(null, record, '工艺文件'),
                ifShow: props.isUpdate,
              },
            ]"
          />
        </template>
      </BasicTable>
    </TabPane>
    <TabPane key="partsList" :tab="t('routes.demo.partManagerSettings.partDetail')">
      <BasicTable @register="partDetailTable" />
    </TabPane>
  </Tabs>
  <!-- 附件类型 -->
  <PartDetailAttachment @register="registerAttachmentType" @addPart="addPart" />
  <!-- 关联 -->
  <partAssign @register="registerPartAssign" @addAssociated="addAssociated" />
  <!-- 共图 -->
  <partModal @register="registerPartModal" @addCommonMap="addCommonMap" />
</template>

<script lang="ts" setup>
  import { ref, onMounted, getCurrentInstance, computed } from 'vue';
  import { Tabs, TabPane, Divider, Tag } from 'ant-design-vue';
  import { BasicForm } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getPartDetailAttachmentColumns, getPartAssociatedColumns } from '../tableData';
  import { getCraftFileColumns, getPartDetailColumns } from './tableData';
  import throttle from 'lodash/throttle';
  import { handleBrowseFile } from '/@/utils/demo/preview';

  import {
    UploadPartFile,
    DeletePartFile,
    getPartAttr,
    GetPartDetail,
  } from '/@/api/demo/partManager';

  import { downloadFile } from '/@/api/demo/document';

  import PartDetailAttachment from '../PartDetailAttachment.vue';
  import partAssign from '../partAssign.vue';
  import partModal from '../partModal.vue';

  const { proxy }: any = getCurrentInstance(); // 获取当前实例
  const props = defineProps({
    // 是否更新
    isUpdate: {
      type: Boolean,
      default: false,
    },
    // 文件夹id
    folderId: {
      type: String,
      default: '',
    },
    // 零件类型
    partType: {
      type: String,
      default: '',
    },
    // 零件属性
    currentRecord: {
      type: Object,
      default: () => ({}),
    },
  });

  onMounted(() => {
    // 获取零件属性详情
    setTimeout(async () => {
      if (props.isUpdate) {
        const res = await GetPartDetail(props.currentRecord.id, props.currentRecord.version);
        partData.value = Array.isArray(res.addPropList) ? res.addPropList : [];
        // 附件
        upLoadFileTypeList.value = Array.isArray(res.faList)
          ? res.faList.map((item) => {
              return {
                fileName: item.fileName,
                docType: item.fileType,
              };
            })
          : [];
        PartDetailAttachmentList.value = Array.isArray(res.faList) ? res.faList : [];
        // 关联
        partGl.value = Array.isArray(res.docToDocList)
          ? res.docToDocList.map((item) => item.oId)
          : [];
        PartAssociatedList.value = Array.isArray(res.docToDocList) ? res.docToDocList : [];
        // 工艺文件
        craftFileList.value = Array.isArray(res.processFileList) ? res.processFileList : [];
        // 零件明细
        partDetailList.value = Array.isArray(res.partBomList) ? res.partBomList : [];
      } else {
        const attrs = await getPartAttr(props.partType);
        partData.value = Array.isArray(attrs) ? attrs : [];
      }
    }, 500);
  });

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const activeKey = ref('basic'); // 默认激活的tab basic属性 attachment附件 related关联 processFile工艺文件 partsList零件明细表
  const partData = ref<any>([]); // 存储零件类型及其属性
  const formRefs = ref<Record<string, any>>({}); // 存储每个 `BasicForm` 实例
  const PartDetailAttachmentList = ref<any>([]); // 附件列表
  const upLoadFileTypeList = ref<any>([]); // 上传文件类型列
  const PartAssociatedList = ref([]); // 关联列表
  const partGl = ref([]); // 关联零件类型
  const partGt = ref<any>([]); // 共同零件类型
  const craftFileList = ref<any>([]); // 工艺文件列表
  const partDetailList = ref<any>([]); // 零件明细表列表
  const propData = ref<any>({}); // 存储属性数据

  const handleTabChange = async () => {
    if (activeKey.value !== 'basic') {
      for (const key in formRefs.value) {
        propData.value[key] = await formRefs.value[key].getFieldsValue();
      }
    }
    if (activeKey.value === 'basic') {
      // 将数据回填到表单
      for (const key in formRefs.value) {
        formRefs.value[key].setFieldsValue(propData.value[key]);
      }
    }
  };

  /**
   * 模块名:
   * 代码描述: 修改状态如果不等于检出，禁用
   * 作者:张泽源
   * 创建时间:2025/05/15 14:33:04
   */
  const isDisabled = computed(() => {
    if (props.isUpdate) {
      return props.currentRecord?.state !== '2';
    }
    return false;
  });

  // 校验表单数据
  const valiDateFormData = async () => {
    // 校验表单
    for (const key in formRefs.value) {
      await formRefs.value[key].validate();
    }
  };

  // 提交零件详情数据
  const getFormData = async () => {
    const params = {
      addPropList: {}, // 零件属性
      aboutIdList: partGt.value, // 共图件
      docToDocList: partGl.value, // 关联件
      upLoadFileTypeList: upLoadFileTypeList.value, // 附件
      partType: props.partType, // 零件类型
      folderId: props.folderId, // 文件夹id
    };
    // 零件属性
    for (const key in formRefs.value) {
      params.addPropList[key] = await formRefs.value[key].getFieldsValue();
    }
    params.addPropList = Object.assign({}, ...Object.values(params.addPropList));
    // 转换 status 中文状态为数字
    const statusMap: Record<string, string> = {
      生效历史版本: '0',
      生效最高版本: '1',
      检出: '2',
      检入审批: '4',
      检出审批: '8',
    };

    // 类型断言 params.addPropList 是一个可以索引的对象
    const addPropList = params.addPropList as Record<string, any>;

    if (addPropList.status && statusMap[addPropList.status]) {
      addPropList.status = statusMap[addPropList.status];
    }
    return params;
  };
  // 让父组件可以调用 getFormData 方法
  defineExpose({ getFormData, valiDateFormData });
  // 附件表格初始化
  const [registerAttachmentTable] = useTable({
    columns: getPartDetailAttachmentColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: false,
    dataSource: PartDetailAttachmentList,
    actionColumn: {
      width: 200,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 提取扩展名函数
  function getExtension(fileName) {
    return fileName.split('.').pop().toLowerCase();
  }

  // 新增附件
  const addPart = (data, file) => {
    // 判断是否允许添加
    const isExist = PartDetailAttachmentList.value.some(
      (item) =>
        item.fileName === data.fileName &&
        item.fileType === data.fileType &&
        getExtension(item.fileName) === getExtension(data.fileName),
    );
    if (isExist) {
      createMessage.error(t('routes.demo.partManager.partDetailModal.attachmentExist'));
    } else {
      const newData = new FormData();
      newData.append('file', file);
      UploadPartFile(newData).then((res) => {
        if (res) {
          PartDetailAttachmentList.value = [...PartDetailAttachmentList.value, data];
          let newData = {
            fileName: data.fileName,
            docType: data.fileType,
          };
          upLoadFileTypeList.value.push(newData);
          createMessage.success(t('common.uploadSuccess'));
        }
      });
    }
  };
  const CreatePartDetailAttachment = () => {
    openAttachmentTypeModal(true, { FolderId: props.folderId });
  };

  // 删除附件
  const DeletePartDetailAttachment = (record) => {
    DeletePartFile(record.fileName).then((res) => {
      if (res) {
        PartDetailAttachmentList.value = PartDetailAttachmentList.value.filter(
          (item) => item.fileName !== record.fileName,
        );
        upLoadFileTypeList.value = upLoadFileTypeList.value.filter(
          (item) => item.fileName !== record.fileName,
        );
        createMessage.success(t('common.delSuccessText'));
      }
    });
  };

  const CreateCommonMap = () => {
    openCommonFigureModal(true, { isWhat: '共图' });
  };

  // 关联表格初始化
  const [registerAssociatedTable] = useTable({
    columns: getPartAssociatedColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: false,
    rowKey: 'thitObjectId',
    dataSource: PartAssociatedList,
    actionColumn: {
      width: 200,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 新增共图
  const addCommonMap = (data) => {
    if (data.fileorpart !== '0') {
      createMessage.warning(t('routes.demo.partManager.partDetailModal.fileType'));
    } else if (data.state !== '8') {
      createMessage.warning(t('routes.demo.partManager.partDetailModal.status'));
    } else {
      const isExist = PartAssociatedList.value.some((item) => item.oId === data.oId);
      if (isExist) {
        createMessage.error(t('routes.demo.partManager.partDetailModal.sharedFigureDocExist'));
      } else {
        let allData = {
          oId: data.oId,
          thitObjectId: data.name,
          version: data.version,
          fileName: data.filename,
          fileType: data.type,
          creater: data.creator,
        };
        PartAssociatedList.value = [...PartAssociatedList.value, allData];
        partGl.value = [...partGl.value, data.id];
      }
    }
  };

  // 新增关联
  const addAssociated = (data) => {
    if (data.fileorpart !== '0') {
      createMessage.warning(t('routes.demo.partManager.partDetailModal.fileType'));
    } else if (data.state !== '8') {
      createMessage.warning(t('routes.demo.partManager.partDetailModal.status'));
    } else {
      const isExist = PartAssociatedList.value.some((item) => item.oId === data.oId);
      if (isExist) {
        createMessage.error(t('routes.demo.partManager.partDetailModal.associated'));
      } else {
        let allData = {
          oId: data.oId,
          thitObjectId: data.name,
          version: data.version,
          fileName: data.filename,
          fileType: data.type,
          creater: data.creator,
        };
        PartAssociatedList.value = [...PartAssociatedList.value, allData];
        partGl.value = [...partGl.value, data.id];
      }
    }
  };

  const CreateAssociated = () => {
    openAssociatedModal(true, { isFrom: '零件关联新增' });
  };

  // 删除关联
  const DeleteAssociated = (data) => {
    PartAssociatedList.value = PartAssociatedList.value.filter((item) => item.oId !== data.oId);
    partGl.value = partGl.value.filter((item) => item !== data.id);
  };

  // 修改
  const EditAssociated = (record) => {
    console.log(record);
    createMessage.warning('该功能暂时不可用');
  };

  // 浏览
  const ViewAssociated = async (record, type) => {
    type === '附件'
      ? await handleBrowseFile(record, '零件附件')
      : type === '关联'
      ? await handleBrowseFile(record, '零件关联')
      : await handleBrowseFile(record, '工艺文件');
  };

  // 下载
  const DownloadAssociated = throttle((record: Recordable) => {
    downloadFile(record.fileId, record.fileVersion, record.fileName).then(() => {
      createMessage.success(t('common.downLoadSuccess'));
    });
  }, 3000);

  // 版本展示
  const VersionAssociated = (record) => {
    console.log(record);
    createMessage.warning('该功能暂时不可用');
  };

  // 绑定表单实例
  const registerForm = (form, key) => {
    formRefs.value[key] = form;
  };

  // 生成 schemas
  const getSchemas = (type, attributes) => {
    if (type === '基本属性') {
      return attributes.map((item) => ({
        field: item.prop,
        label: item.label,
        component: filterOption(item.attr),
        defaultValue:
          item.label === '状态' ? proxy.$filters.filterPartStatus(item.value) : item.value,
        componentProps: {
          disabled: props.isUpdate
            ? props.currentRecord.state !== '2'
              ? true
              : filterUpdate(item.label)
            : filterAdd(item.label),
          options:
            filterOption(item.attr) === 'Select'
              ? item.dataSource.map((i) => ({ label: i.name, value: i.id }))
              : [],
        },
        colProps: {
          xl: 12,
          xxl: 12,
        },
        required: item.pdmnull === 0, // 0是必填， 1是非必填
      }));
    } else {
      return attributes.map((item) => ({
        field: item.prop,
        label: item.label,
        component: filterOption(item.attr),
        defaultValue: item.value,
        componentProps: {
          disabled: props.isUpdate
            ? props.currentRecord.state !== '2'
              ? true
              : filterReadOnly(item.attr)
            : filterReadOnly(item.attr),
          options:
            filterOption(item.attr) === 'Select'
              ? item.dataSource.map((i) => ({ label: i.name, value: i.id }))
              : [],
        },
        colProps: {
          xl: 12,
          xxl: 12,
        },
        required: item.pdmnull === 0, // 0是必填， 1是非必填
      }));
    }
  };

  // attr过滤控件方法
  const filterOption = (type) => {
    // 文本框
    const textArr = ['4101', '256', '21', '17', '264', '4100', '1'];
    // 下拉框
    const selectArr = ['145', '128', '136', '384', '392', '640'];
    // 选用日历
    const dateArr = ['8448', '8456'];
    // 资源控件
    const resourceArr = ['1024', '1032', '1280', '1288'];
    // 资源控件多选
    const resourceMultiArr = ['768', '776'];
    // 选择框
    const checkboxArr = ['16384', '16392'];
    // 网格
    const gridArr = ['512', '520'];
    // 下拉选择数据源
    const selectDataSourceArr = ['131072', '131080'];
    // 关联文件
    const relatedFileArr = ['262144', '262152'];
    // 下拉多选
    const selectMultiArr = ['32768', '32776'];
    if (textArr.includes(type)) {
      return 'Input';
    } else if (selectArr.includes(type)) {
      return 'Select';
    } else if (dateArr.includes(type)) {
      return 'DatePicker';
    } else if (resourceArr.includes(type)) {
      return 'Select';
    } else if (resourceMultiArr.includes(type)) {
      return 'Select';
    } else if (checkboxArr.includes(type)) {
      return 'Checkbox';
    } else if (gridArr.includes(type)) {
      return 'Input';
    } else if (selectDataSourceArr.includes(type)) {
      return 'Select';
    } else if (relatedFileArr.includes(type)) {
      return 'Input';
    } else if (selectMultiArr.includes(type)) {
      return 'Select';
    } else {
      return '';
    }
  };
  // attr 过滤只读属性
  const filterReadOnly = (type) => {
    const readOnlyList = [
      '264',
      '136',
      '392',
      '648',
      '8456',
      '1032',
      '1288',
      '776',
      '16392',
      '520',
      '131080',
      '262152',
      '32776',
    ];
    if (readOnlyList.includes(type)) {
      return true;
    } else {
      return false;
    }
  };
  // label过滤新增可操作属性
  const filterAdd = (type) => {
    const labelList = ['零件代号', '零件名称'];
    if (labelList.includes(type)) {
      return false;
    } else {
      return true;
    }
  };
  // label过滤修改可操作属性
  const filterUpdate = (type) => {
    const labelList = ['零件名称', '零件类型'];
    if (labelList.includes(type)) {
      return false;
    } else {
      return true;
    }
  };

  // 工艺文件
  const [craftFileTable] = useTable({
    columns: getCraftFileColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: false,
    rowKey: 'id',
    dataSource: craftFileList,
    actionColumn: {
      width: 200,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 零件明细表
  const [partDetailTable] = useTable({
    columns: getPartDetailColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: false,
    rowKey: 'id',
    dataSource: partDetailList,
  });

  // 附件类型
  const [registerAttachmentType, { openModal: openAttachmentTypeModal }] = useModal();
  // 关联
  const [registerPartAssign, { openModal: openAssociatedModal }] = useModal();
  // 共图
  const [registerPartModal, { openModal: openCommonFigureModal }] = useModal();
</script>

<style lang="less" scoped></style>
